<?php

namespace App\Controller;

use App\Common\User;
use App\Common\Utils\ResponseUtils;
use App\Entity\Product;
use App\Listener\SystemException;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class ProductController extends AbstractController
{

    private $logger;
    private $validator;

    /**
     * ProductController constructor.
     * @param $logger
     * @param $validator
     */
    public function __construct(LoggerInterface $logger, ValidatorInterface $validator)
    {
        $this->logger = $logger;
        $this->validator = $validator;
    }


    /**
     * @Route(path="/products", name="product_add", methods={"POST"})
     * @param SerializerInterface $serializer
     * @param Request $request
     * @return JsonResponse
     * @throws SystemException
     */
    public function creatProduct(SerializerInterface $serializer, Request $request)
    {
        $product = $serializer->deserialize($request->getContent(), Product::class, "json");

        $errors = $this->validator->validate($product);
        if (count($errors) > 0) {
            throw new SystemException($errors->get(0)->getMessage());
        }

        $entityManager = $this->getDoctrine()->getManager();

        $entityManager->persist($product);
        $entityManager->flush();

        return ResponseUtils::success($product);
    }

    /**
     * @Route(path="/products", name="product_list", methods={"GET"})
     */
    public function getProducts() {
        $repository = $this->getDoctrine()->getRepository(Product::class);

        $results = $repository->findAllProducts();

        return ResponseUtils::success($results);
    }
}
